package com.jinyuanchun.self.covid19;

import jdk.nashorn.internal.runtime.regexp.joni.Regex;
import org.apache.commons.net.ftp.FTPClient;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DownloadByList {
    public static void main(String[] args) {
        if (args.length != 2) {
            System.out.println("命令行运行格式如下：");
            System.out.println("\tjava downloadByList infile outdir");
            System.exit(1);
        }
        String fileName = args[0];
        String outDir = args[1];
//        ReadFromFile.readByLines(fileName);
        Map<String,Map<String,String>> fileHash = ReadFromFile.read2Hash(fileName,"Sequence_ID");

        // 连接ftp
        FtpUtils ftpUtils = new FtpUtils();
        FTPClient ftp = ftpUtils.getFTPClient("10.50.10.2",21,"anonymous","");
        // 下载文件
        for(Map.Entry<String,Map<String,String>> entry:fileHash.entrySet()){
//            System.out.println("key = "+entry.getKey()+"\tvalue = "+entry.getValue().toString());
            String key = entry.getKey();
            Map<String,String> map = entry.getValue();
            Integer length = Integer.valueOf(map.get("Length"));
            String ftpFile = map.get("Files");
            String id = map.get("Sequence_ID");
            // 获取路径和文件名
            File file = new File(ftpFile);
            String ftpFilePath = file.getPath(); // 获取文件所在的目录
            String ftpDir = get_dir(file.getParent()); // 获取文件所在的目录
//            System.out.println(ftpDir);
            String ftpName = file.getName();
            String outName = get_name(id,ftpName);

            // 当长度大于20k时，下载序列
            if (length>20000){
                ftpUtils.downLoadFTP(ftp,ftpDir,ftpName,outDir,outName);
            }
        }
        // 关闭 ftp
        ftpUtils.closeFTP(ftp);
    }

    private static String get_name(String id, String ftpName) {
        String pattern = "\\.gz$";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(ftpName);
        String result = "";
        if (m.find()){
            result = id+".fa.gz";
        } else {
            result = id+".fa";
        }
        return result;
    }

    private static String get_dir(String parent) {
        String[] tmp = parent.split("\\\\");
        String result = "";
        for(int i=2;i<tmp.length;i++){
            result += tmp[i]+"/";
        }
        return result;
    }
}
